/*
*************************************
* PocketGTT
*************************************
This file is part of PocketGTT.

PocketGTT is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

PocketGTT is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with PocketGTT.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "localdebug.h"
#include "gtt_preferredstoplist.h"
#include "gtt_preferredstop.h"
#include <QTextStream>
#include <QDebug>
#include <QDesktopServices>
#include <QIODevice>
#include <QDir>


GTT_PreferredStopList::GTT_PreferredStopList(QDeclarativeContext *ctx, QObject *parent) :
    QObject(parent), hiddenCtx(ctx)
{

    // connect list change signal with the slot that updates QML
    connect(this, SIGNAL(onPreferredListChanged()),this, SLOT(informQML()));

    //create List of preferred Stops from XML saved file
    // file path depending on OS
#ifdef Q_WS_MAEMO_5
    QString path(QDir::home().path());
//    qDebug() << path;
    myPrivateFile = path.append("/.PocketGTT");
    if(!QDir(myPrivateFile).exists())
        qDebug() << "not exists: " << myPrivateFile;
    QDir().mkpath(myPrivateFile);
#else
    myPrivateFile = QString(QDesktopServices::storageLocation (QDesktopServices::DataLocation));
#endif

    myPrivateFile.append("/PreferredStops.xml");

#if ATTIVADEBUG
    qDebug() << myPrivateFile;
#endif

    //check with  Qfile if already exists e preferred xml file otherwise load the basic one in resource file
    QFile myFile;

    if (!QFile(myPrivateFile).exists()) {

#if ATTIVADEBUG
        qDebug() << "file not exists";
#endif

        //load basic file from resource file
        myFile.setFileName(":/PreferredStops_Startup.xml");

    }
    else {

#if ATTIVADEBUG
        qDebug() << "file  exists";
#endif

        //load already managed user file from filesystem
        myFile.setFileName(myPrivateFile);
    }

    fillList(&myFile);

    myFile.close();

    emit onPreferredListChanged();

}

void GTT_PreferredStopList::addElement(const QString &number, const QString &name, const QString &street)
{
    if (preferredList.size() > 0 ) {
        int m_index = -1;

        for (int i=0; i<preferredList.size(); i++)
        {
            QObject *pStop = preferredList.at(i);

            GTT_PreferredStop *myStop =  qobject_cast<GTT_PreferredStop *>(pStop);

            if(myStop->stopNumber() == number)
                m_index = i;

        }
        //        int m_index = preferredList.indexOf(new GTT_PreferredStop(number, name, street));
        if ( m_index != -1) {
            preferredList.move(m_index, 0);

        }
        else {
            preferredList.insert(0, new GTT_PreferredStop(number, name, street));
        }

    }

    else {
        qDebug() << "appendo nuova fermata: " << number;
        preferredList.append(new GTT_PreferredStop(number, name, street));
    }
    // after list update restore the context for QML update (hopefully)
    emit onPreferredListChanged();
}

QString GTT_PreferredStopList::getTitle(const QString &item)
{
    bool num_ok = false;
    int nItem = item.toInt(&num_ok, 10);
    QString titleStr = "";
    if (( preferredList.size() > nItem)&& num_ok) {
        GTT_PreferredStop *myStop =  qobject_cast<GTT_PreferredStop *>(preferredList.at(nItem));
        //        preferredList.at(nItem)->
        titleStr = myStop->stopName();
        titleStr.append(" (").append(myStop->stopNumber()).append(")");
    }
    return titleStr;
    //    listSize() > 1
}

void GTT_PreferredStopList::informQML()
{
    hiddenCtx->setContextProperty("GTT_preferredStopList", QVariant::fromValue(preferredList));
}

int GTT_PreferredStopList::fillList(QFile *myFile)
{
    if (!myFile->open(QIODevice::ReadOnly | QIODevice::Text)) {
#if ATTIVADEBUG
        qDebug() << "startup file not opened";
#endif

        return -1;
    }
    else{
#if ATTIVADEBUG
        qDebug() << "startup file  opened";
#endif

        QDomDocument doc( "GTTPreferredStops" );
        if( !doc.setContent( myFile ) ) {
#if ATTIVADEBUG
            qDebug() << "problema con XML startup lettura";
#endif

            return -2;
        }
        else {

            QDomElement root = doc.documentElement();
            if( root.tagName() != "stoplist" ) {
#if ATTIVADEBUG
                qDebug() << "tag errato";
#endif
                return -3;
            }

            QDomNode n = root.firstChild();
            while( !n.isNull() )
            {
                QDomElement e = n.toElement();
                if( !e.isNull() )
                {
                    if( e.tagName() == "stop" )
                    {

                        preferredList.append(
                                    new GTT_PreferredStop(e.attribute( "number", "" ), e.attribute( "name", "" ), e.attribute( "street", "" ))
                                    );
                    }
                }

                n = n.nextSibling();
            }
        }
        return 0;
    }
}

int GTT_PreferredStopList::savePreferredList2XML() {

    // build up DOM structure
    QDomDocument myDoc("GTTPreferredStops");
    QDomElement docRoot = myDoc.createElement( "stoplist" );
    myDoc.appendChild( docRoot );

    foreach (QObject *pStop, preferredList) {
        GTT_PreferredStop *myStop =  qobject_cast<GTT_PreferredStop *>(pStop);
        docRoot.appendChild( Stop2Node( &myDoc, myStop ) );
    };

    QFile file( myPrivateFile);
    if( !file.open( QIODevice::WriteOnly ) )
        return 0;

    QTextStream ts( &file );
    ts << myDoc.toString();

#if ATTIVADEBUG
    qDebug() << myDoc.toString();
#endif

    file.close();

    return 1;

}

QDomElement GTT_PreferredStopList::Stop2Node( QDomDocument *d, GTT_PreferredStop *s )
{
    QDomElement cn = d->createElement( "stop" );

    cn.setAttribute( "name", s->stopName() );
    cn.setAttribute( "number", s->stopNumber() );
    cn.setAttribute( "street", s->stopStreet() );

    return cn;
}


QString GTT_PreferredStopList::getFirstPreferred() {
    GTT_PreferredStop *myStop =  qobject_cast<GTT_PreferredStop *>(preferredList.at(0));
    return myStop->stopNumber();
}

void  GTT_PreferredStopList::removePreferred(int i) {

    preferredList.removeAt(i);
    emit onPreferredListChanged();


}

int GTT_PreferredStopList::listSize() {
    return preferredList.size();
}
